package com.tian.scroll.gesture.fragment;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.VelocityTracker;
import android.view.View;
import android.widget.RelativeLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.tian.scroll.gesture.custom.RotateGestureDetector;


/**
 * @author tiansongtao, Email:tiansongtao@up366.com
 * @date 2021/1/19 17:06
 */
public class RotationRelativeLayout extends RelativeLayout {
    
    private static final String TAG = "RotationRelativeLayout";
    
    private RotateGestureDetector gestureDetector;
    private VelocityTracker  tracker;

    public RotationRelativeLayout(@NonNull Context context) {
        super(context);
        init();
    }

    public RotationRelativeLayout(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public RotationRelativeLayout(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private View view;

    private float startRotation;

    private void init() {
        tracker = VelocityTracker.obtain();
        gestureDetector = new RotateGestureDetector(getContext(), new RotateGestureDetector.OnRotateGestureListener() {
            @Override
            public boolean onRotate(RotateGestureDetector detector) {
                View view = getChildAt(0);
                Log.i(TAG, "onRotate:  add rotation" + detector.getRotationDegreesDelta());
                view.setRotation(startRotation - detector.getRotationDegreesDelta()); 
                return false;
            }

            @Override
            public boolean onRotateBegin(RotateGestureDetector detector) {
                view = getChildAt(0);
                startRotation = view.getRotation();
                Log.i(TAG, "onRotateBegin: view current rotation" + startRotation);
                return true;
            }

            @Override
            public void onRotateEnd(RotateGestureDetector detector) {
                tracker.computeCurrentVelocity(1000);
                Log.i(TAG, "onRotateEnd: velocity x=" + tracker.getXVelocity(-1) + "  y=" + tracker.getYVelocity(-1) );


            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        tracker.recycle();
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        tracker.addMovement(event);
        return gestureDetector.onTouchEvent(event);
    }
}
